package com.zis.platform.common.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.util.CollectionUtils;

import com.zis.platform.common.authentication.CoreAuthorizingRealm;
import com.zis.platform.core.entity.AreaEntity;
import com.zis.platform.core.entity.DataAuthStrategyEntity;
import com.zis.platform.core.entity.DictionaryEntity;
import com.zis.platform.core.entity.DictionaryTypeEntity;
import com.zis.platform.core.entity.SysEntity;
import com.zis.util.CacheUtil;
import com.zis.util.URLHelper;

/**
 * 
 * <b>说明：</b>缓存工具类
 * 
 * @ClassName: CacheCoreUtil
 * @author zhaohaitao(2543)
 * @date 2015-7-10 上午10:19:15
 * 
 */
public class CacheCoreUtil
{
    private static Logger log = Logger.getLogger(CacheCoreUtil.class);
    
    // 系统启动状态
    private static final String SYSTEM_START_STATE = "_system_start_state_";
    
    // 业务应用系统缓存 key
    private static final String SYS_CONFIG_CACHE_KEY = "_system_info_cache_";
    
    // 数据字典缓存名称
    private static final String DICTIONARY_CACHE_KEY = "_dictionary_info_cache_";
    
    // 数据权限策略缓存名称
    private static final String DATA_AUTH_STRATEGY_CACHE_KEY = "_data_auth_strategy_cache_";
    
    // 字典类型缓存名称
    private static final String DICTIONARY_TYPE_CACHE_KEY = "_dictionary_type_info_cache_";
    
    // Shiro权限管理模块缓存名称
    private static final String SHIRO_CACHE_MANAGER_NAME = CoreAuthorizingRealm.class.getName() + ".authorizationCache";
    
    /**
     * 从缓存中获取应用信息
     * 
     * @param req
     * @return
     */
    @SuppressWarnings("unchecked")
    public static SysEntity getSysInfo(HttpServletRequest req)
    {
        String sysContentPath = URLHelper.getSysContentPath(req);
        Map<String, SysEntity> sysConfigData = (Map<String, SysEntity>)CacheUtil.get(SYS_CONFIG_CACHE_KEY);
        if (sysConfigData != null)
        {
            return sysConfigData.get(sysContentPath);
        }
        else
        {
            log.error("缓存中未找到应用路径为： [" + sysContentPath + "] 的系统信息");
        }
        return null;
    }
    
    @SuppressWarnings("unchecked")
    public static List<SysEntity> getSysInfos()
    {
        Map<String, SysEntity> sysConfigData = (Map<String, SysEntity>)CacheUtil.get(SYS_CONFIG_CACHE_KEY);
        if (sysConfigData != null)
        {
            Set<String> keySet = sysConfigData.keySet();
            List<SysEntity> sysInfos = new ArrayList<SysEntity>();
            for (String sysId : keySet)
            {
                SysEntity sysEntity = sysConfigData.get(sysId);
                sysInfos.add(sysEntity);
            }
            return sysInfos;
        }
        else
        {
            log.error("缓存中未找到应用系统信息");
        }
        return null;
    }
    
    @SuppressWarnings("unchecked")
    public static SysEntity getSysInfoBySysId(String sysId)
    {
        Map<String, SysEntity> sysConfigData = (Map<String, SysEntity>)CacheUtil.get(SYS_CONFIG_CACHE_KEY);
        if (sysConfigData != null)
        {
            return sysConfigData.get(sysId);
        }
        else
        {
            log.error("缓存中未找到应用系统信息");
        }
        return null;
    }
    
    /**
     * 将数据库应用数据放入缓存
     * 
     * @param systems
     */
    public static void cacheSysInfo(List<SysEntity> systems)
    {
        try
        {
            if (systems != null && systems.size() > 0)
            {
                log.debug("开始  缓存系统数据");
                Map<String, SysEntity> sysMap = new HashMap<String, SysEntity>();
                for (SysEntity sys : systems)
                {
                    sysMap.put(sys.getContentPath(), sys);
                }
                CacheUtil.put(SYS_CONFIG_CACHE_KEY, sysMap);
                log.debug("结束  缓存系统数据");
            }
            else
            {
                log.error("系统数据为空，请先配置系统数据");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * 刷新应用信息缓存
     * 
     * @param systems
     */
    public static void refreshSysInfo(List<SysEntity> systems)
    {
        CacheUtil.remove(SYS_CONFIG_CACHE_KEY);
        cacheSysInfo(systems);
    }
    
    /**
     * 将用户区域信息写入缓存
     * 
     * @param systems
     */
    public static void cacheAreaInfo(List<AreaEntity> areas)
    {
        try
        {
            if (!CollectionUtils.isEmpty(areas))
            {
                log.debug("开始  缓存系统数据");
                Map<String, AreaEntity> sysMap = new HashMap<String, AreaEntity>();
                for (AreaEntity area : areas)
                {
                    sysMap.put(area.getAreaCode(), area);
                }
                CacheUtil.put(SYS_CONFIG_CACHE_KEY, sysMap);
                log.debug("结束  缓存系统数据");
            }
            else
            {
                log.error("系统数据为空，请先配置系统数据");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * 将字典数据写入缓存
     * 
     * @param dicTypes
     */
    public static void cacheDictionary(List<DictionaryTypeEntity> dicTypes)
    {
        if (!CollectionUtils.isEmpty(dicTypes))
        {
            Map<String, DictionaryEntity> dataMap = new HashMap<String, DictionaryEntity>();
            Map<String, DictionaryTypeEntity> dataTypeMap = new HashMap<String, DictionaryTypeEntity>();
            for (DictionaryTypeEntity type : dicTypes)
            {
                dataTypeMap.put(type.getDictTypeCode(), type);
                List<DictionaryEntity> dics = type.getDics();
                for (DictionaryEntity dic : dics)
                {
                    dataMap.put(dic.getDictValue(), dic);
                }
            }
            CacheUtil.put(DICTIONARY_TYPE_CACHE_KEY, dataTypeMap);
            CacheUtil.put(DICTIONARY_CACHE_KEY, dataMap);
        }
    }
    
    /**
     * 根据字典值 获取字典名称
     * 
     * @param dicValue
     * @return
     */
    public static DictionaryEntity getDictionaryByValue(String dicValue)
    {
        Map<String, DictionaryEntity> dataMap = (Map<String, DictionaryEntity>)CacheUtil.get(DICTIONARY_CACHE_KEY);
        if (!CollectionUtils.isEmpty(dataMap))
        {
            return dataMap.get(dicValue);
        }
        return null;
    }
    
    /**
     * 从缓存中读取字典类型数据 (包含下属的所有字典数据)
     * 
     * @param typeCode
     * @return
     */
    public static DictionaryTypeEntity getDictionaryType(String typeCode)
    {
        Map<String, DictionaryTypeEntity> dataMap =
            (Map<String, DictionaryTypeEntity>)CacheUtil.get(DICTIONARY_TYPE_CACHE_KEY);
        if (!CollectionUtils.isEmpty(dataMap))
        {
            return dataMap.get(typeCode);
        }
        return null;
    }
    
    /**
     * 刷新 字典类型数据
     * 
     * @param systems
     */
    public static void refreshDictionaryType(List<DictionaryTypeEntity> types)
    {
        CacheUtil.remove(DICTIONARY_CACHE_KEY);
        CacheUtil.remove(DICTIONARY_TYPE_CACHE_KEY);
        cacheDictionary(types);
    }
    
    /**
     * 将数据权限策略写入缓存
     * 
     * @param strategy
     */
    public static void cacheDataAuthStrategy(List<DataAuthStrategyEntity> strategy)
    {
        if (!CollectionUtils.isEmpty(strategy))
        {
            Map<String, DataAuthStrategyEntity> dataMap = new HashMap<String, DataAuthStrategyEntity>();
            for (DataAuthStrategyEntity s : strategy)
            {
                dataMap.put(s.getTableName().toUpperCase(), s);
            }
            CacheUtil.put(DATA_AUTH_STRATEGY_CACHE_KEY, dataMap);
        }
    }
    
    /**
     * 从缓存中读取所有的数据权限策略
     * 
     * @return Map<String, DataAuthStrategyEntity>
     */
    public static Map<String, DataAuthStrategyEntity> getAllDataAuthStrategy()
    {
        Map<String, DataAuthStrategyEntity> dataMap =
            (Map<String, DataAuthStrategyEntity>)CacheUtil.get(DATA_AUTH_STRATEGY_CACHE_KEY);
        return dataMap;
    }
    
    /**
     * 刷新数据权限策略缓存
     * 
     * @param types
     */
    public static void refreshDataAuthStrategyType(List<DataAuthStrategyEntity> strategy)
    {
        CacheUtil.remove(DATA_AUTH_STRATEGY_CACHE_KEY);
        cacheDataAuthStrategy(strategy);
    }
    
    /**
     * 缓存系统启动状态
     * 
     * @param isStarted
     */
    public static void cacheSystemStartState(boolean isStarted)
    {
        CacheUtil.put(SYSTEM_START_STATE, isStarted);
    }
    
    public static Boolean getSystemStartState()
    {
        Boolean isStarted = (Boolean)CacheUtil.get(SYSTEM_START_STATE);
        return isStarted;
    }
}
